package registereds

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ RegisteredsModel = (*customRegisteredsModel)(nil)

type (
	// RegisteredsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customRegisteredsModel.
	RegisteredsModel interface {
		registeredsModel
		FindByCardNoDeptAndDoctor(ctx context.Context, cardNo, deptId string) ([]*Registereds, error)
		FindByCardNo(ctx context.Context, cardNo string) ([]Registereds, error)
		FindAll(ctx context.Context) ([]Registereds, error)
	}

	customRegisteredsModel struct {
		*defaultRegisteredsModel
	}
)

// NewRegisteredsModel returns a model for the database table.
func NewRegisteredsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) RegisteredsModel {
	return &customRegisteredsModel{
		defaultRegisteredsModel: newRegisteredsModel(conn, c, opts...),
	}
}

func (m *defaultRegisteredsModel) FindByCardNoDeptAndDoctor(ctx context.Context, cardNo, deptId string) ([]*Registereds, error) {
	callsystemRegisteredsRegisteredcodeKey := fmt.Sprintf("%s%v", cacheCallsystemRegisteredsRegisteredcodePrefix, cardNo+"_"+deptId)
	var resp []*Registereds
	err := m.QueryRowIndexCtx(ctx, &resp, callsystemRegisteredsRegisteredcodeKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
		query := fmt.Sprintf("select %s from %s where cardno=? and (deptid=? or deptid is null)", registeredsRows, m.table)
		fmt.Printf("SQL:%v", query)
		if err := conn.QueryRowCtx(ctx, &resp, query, cardNo, deptId); err != nil {
			return nil, err
		}
		return resp, nil
	}, m.queryPrimary)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultRegisteredsModel) FindByCardNo(ctx context.Context, cardNo string) ([]Registereds, error) {
	var resp []Registereds
	query := fmt.Sprintf("select %s from %s where cardno=?", registeredsRows, m.table)
	err := m.QueryRowsNoCacheCtx(ctx, &resp, query, cardNo)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultRegisteredsModel) FindAll(ctx context.Context) ([]Registereds, error) {
	var resp []Registereds
	query := fmt.Sprintf("select %s from %s", registeredsRows, m.table)
	err := m.QueryRowsNoCacheCtx(ctx, &resp, query)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
